use apikit::rpc::{ResponseParamSign, sse_client::FromEvent};
use reqwest_eventsource::Event;
use serde::{Serialize, de::DeserializeOwned};

use crate::param::{SseResponse, __TypeMapper};

pub struct TypedEvent<T> {
    pub origin: reqwest_eventsource::Event,
    pub data: Option<T>,
}

impl<T: Serialize, E> ResponseParamSign<Result<SseResponse<T>, E>> for __TypeMapper {
    type Output = TypedEvent<T>;
}

impl<T: DeserializeOwned> FromEvent<Event> for TypedEvent<T> {
    type Error = serde_json::Error;

    fn from_event(event: Event) -> Result<Self, Self::Error> {
        let mut data = None;
        if let Event::Message(message) = &event {
            let decoded = serde_json::from_str(&message.data)?;
            data = Some(decoded);
        }
        Ok(Self {
            origin: event,
            data,
        })
    }
}
